package com.hellobike.haxing.modules.coupon.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.coupon.entity.CouponPackage;
import com.hellobike.haxing.modules.coupon.service.ICouponPackageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 券包
 * @Author: haxing-boot
 * @Date: 2020-02-01
 * @Version: V1.0
 */
@RestController
@RequestMapping("/coupon/couponPackage")
@Slf4j
public class CouponPackageController extends BaseController<CouponPackage, ICouponPackageService> {
    @Autowired
    private ICouponPackageService couponPackageService;

    /**
     * 分页列表查询
     *
     * @param couponPackage
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "券包-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CouponPackage couponPackage,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<CouponPackage> queryWrapper = QueryGenerator.initQueryWrapper(couponPackage, req.getParameterMap());
        Page<CouponPackage> page = new Page<CouponPackage>(pageNo, pageSize);
        IPage<CouponPackage> pageList = couponPackageService.page(page, queryWrapper);
        if (CollectionUtils.isNotEmpty(pageList.getRecords())) {
            for (CouponPackage cp : pageList.getRecords()) {
                if (cp.getCouponIds() != null
                        && cp.getCouponIds().size() > 0
                        && (cp.getCouponInfo() == null || cp.getCouponInfo().size() < 1)) {
                    cp.setCouponInfo(new JSONArray());
                    for (int i = 0; i < cp.getCouponIds().size(); i++) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("id", cp.getCouponIds().getLongValue(i));
                        jsonObject.put("count", 1);
                        cp.getCouponInfo().add(jsonObject);
                    }
                }
            }
        }
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param couponPackage
     * @return
     */
    @AutoLog(value = "券包-添加", operateType = 2)
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CouponPackage couponPackage) {
        couponPackageService.save(couponPackage);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param couponPackage
     * @return
     */
    @AutoLog(value = "券包-编辑", operateType = 3)
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CouponPackage couponPackage) {
        couponPackage.setSendedNum(null);//更新时忽略该字段
        couponPackageService.updateById(couponPackage);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "券包-删除", operateType = 4)
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) Long id) {
        couponPackageService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "券包-批量删除", operateType = 4)
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.couponPackageService.removeByIds(Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) Long id) {
        CouponPackage couponPackage = couponPackageService.getById(id);
        if (couponPackage == null) {
            return Result.error("未找到对应数据");
        }
        if (couponPackage.getCouponIds() != null && couponPackage.getCouponIds().size() > 0 && (couponPackage.getCouponInfo() == null || couponPackage.getCouponInfo().size() < 1)) {
            couponPackage.setCouponInfo(new JSONArray());
            for (int i = 0; i < couponPackage.getCouponIds().size(); i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", couponPackage.getCouponIds().getLongValue(i));
                jsonObject.put("count", 1);
                couponPackage.getCouponInfo().add(jsonObject);
            }
        }
        return Result.ok(couponPackage);
    }

    @GetMapping(value = "/queryByIds")
    public Result<?> queryByIds(@RequestParam(name = "id", required = true) String ids) {

        if (StringUtils.isNotBlank(ids)) {
            String[] strs = ids.split(",");
            List<Long> idList = new ArrayList<>();
            for (String str : strs) {
                idList.add(Long.valueOf(str));
            }
            List<CouponPackage> couponPackages = couponPackageService.list(new QueryWrapper<CouponPackage>()
                    .lambda().in(CouponPackage::getId, idList));
            return Result.ok(couponPackages);
        }
        return Result.ok(null);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param couponPackage
     */
    @AutoLog(value = "券包-导出excel", operateType = 6)
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CouponPackage couponPackage) {
        return super.exportXls(request, couponPackage, CouponPackage.class, "券包");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "券包-导入excel", operateType = 5)
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CouponPackage.class);
    }

}
